//
//  XXTripTableViewController.m
//  TravelFollowYourHeart
//
//  Created by 鲁万玺 on 2017/12/27.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "XXTripTableViewController.h"
#import <MapKit/MapKit.h>
//#import "XXTripTableViewCell.h"
//#import "XXTripHeaderView.h"
#import "TripTableViewCell.h"
#import "TripHeaderView.h"
#import "XXTripModel.h"
#import "ChooseJourneyViewController.h"
#import "XXTripCellModel.h"
#import "MyJourneyViewController.h"

@interface XXTripTableViewController ()<TripHeaderViewDelegate, UITableViewDelegate, UITableViewDataSource, MKAnnotation, MKMapViewDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)MKMapView *mapView;
@property (nonatomic, strong)XXTripModel * model;
@property (nonatomic, strong)NSArray * headModel;
@property (nonatomic, assign)int days;
@property (nonatomic, assign)int addToDayth;//添加第几天的行程
@property (nonatomic, strong)XXTripCellModel * cellModel;//tableView数据
@property (nonatomic, strong)XXTripCellModelData * cellModelData;//为了拿到经纬度
@property (nonatomic, assign)int dayNum;
@property (nonatomic, retain)NSMutableArray * titudeArr;//经纬度数组
@property (nonatomic, retain)NSMutableArray * locationArr;//存放大头针组
@property (nonatomic, retain)NSMutableArray * switchArr;//中转数组
@property (nonatomic, strong)NSString * journeyName;
@end

@implementation XXTripTableViewController(Networking)
//进入页面接收数据的接口
- (void)getCellData{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"trip_id":@(self.trip_id)
                           };
    WS(ws)
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/index/TripDetail") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                self.titudeArr=obj[@"data"];
                ws.cellModel = [XXTripCellModel yy_modelWithDictionary:obj];
                self.tableView.tableHeaderView = self.mapView;
                [self.tableView reloadData];
            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
            }
        }
    }];
}

- (void)deleteCellTripID:(NSString *)trip_id withDay:(int)day{
    NSDictionary * dic = @{
                           @"day":@(day),
                           @"tid":@(self.tid),
                           @"trip_id":@(self.trip_id)
                           };
//    WS(ws)
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/index/delOneday") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                [self.tableView reloadData];
            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
                [self.tableView reloadData];

            }
        }
    }];
}
//点击生成行程
- (void)createJourneyName:(NSString *)name{
    NSDictionary * dic = @{
                           @"trip_id":@(self.trip_id),
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"name":name
                           };
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/editTrip") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                [self.tableView reloadData];
                MyJourneyViewController * myJourneyVC = [[MyJourneyViewController alloc] init];
                [self.navigationController pushViewController:myJourneyVC animated:YES];
            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
                [self.tableView reloadData];
            }
        }
    }];
}

@end

@implementation XXTripTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"行程";
    self.view.backgroundColor = getColor(bgColor);
    self.locationArr = [NSMutableArray array];
    self.switchArr = [NSMutableArray array];
    self.titudeArr = [NSMutableArray array];
    
    [self getCellData];
    
    int nextStepBtnH = 50;
    UIButton * nextStepBtn = [[UIButton alloc] init];
    nextStepBtn.frame = CGRectMake(0, SCREEN_HEIGHT - nextStepBtnH - 64, SCREEN_WIDTH, nextStepBtnH);
    [nextStepBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextStepBtn setTitle:@"生成行程" forState:UIControlStateNormal];
    nextStepBtn.backgroundColor = [UIColor themeColor];
    nextStepBtn.titleLabel.font = DEF_FontSize_14;
    [nextStepBtn addTarget:self action:@selector(nextStepBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextStepBtn];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - nextStepBtnH) style:UITableViewStylePlain];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - nextStepBtnH);
    self.tableView.backgroundColor = getColor(bgColor);
    [self.view addSubview:self.tableView];
}

- (MKMapView *)mapView
{
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
        _mapView.mapType = MKMapTypeStandard;//标准模式
        _mapView.showsUserLocation = YES;//显示自己
        _mapView.zoomEnabled = YES;//支持缩放
        _mapView.delegate = self;
        for (int x = 0 ; x<self.cellModel.data.count; x++) {
            for (int y = 0; y<[self.cellModel.data[x] count]; y++) {
                NSString * latStr = [self.titudeArr[x][y] objectForKey:@"lat"];
                NSString * lngStr = [self.titudeArr[x][y] objectForKey:@"lng"];
                float latFloat = [latStr floatValue];
                float lngFloat = [lngStr floatValue];
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                [annotation setCoordinate:CLLocationCoordinate2DMake(latFloat, lngFloat)];
                [self.switchArr insertObject:annotation atIndex:y];
                [self.mapView addAnnotation:annotation];
                
            }
            [self.locationArr insertObject:self.switchArr atIndex:x];
        }
    }return _mapView;
}

- (NSArray *)headModel{
    if (!_headModel) {
        _headModel = @[@"第一天", @"第二天", @"第三天"];
    }return _headModel;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return self.cellModel.data.count;
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"selectTravelDays"] intValue] == 0) {
        return self.cellModel.data.count;
//    }else{
//        return [[[NSUserDefaults standardUserDefaults] objectForKey:@"selectTravelDays"] intValue];
//    }
    
//    return self.selectTravelDays;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (section == 0) {
//        return self.oneDay.count;
//    }
//    if (section == 1) {
//        return self.twoDay.count;
//    }else{
//        return self.threeDay.count;
//    }
    return [self.cellModel.data[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"cell";
    [self.tableView registerClass:[TripTableViewCell class] forCellReuseIdentifier:cellID];
    TripTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    if (!cell) {
        cell = [[TripTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.modelData = self.cellModel.data[indexPath.section][indexPath.row];
    NSString * cellTripID = cell.modelData.tid;
    WS(ws)
    cell.block = ^(){
        [ws.cellModel.data[indexPath.section] removeObjectAtIndex:indexPath.row];
        [ws.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        if (indexPath.section == 0) {
            self.dayNum = 1;
        }if (indexPath.section == 1) {
            self.dayNum = 2;
        }if (indexPath.section == 2) {
            self.dayNum = 3;
        }
        self.tid = [cellTripID intValue];
        [ws deleteCellTripID:[NSString stringWithFormat:@"%i",self.trip_id] withDay:self.dayNum];
        [self.mapView removeAnnotation:self.locationArr[indexPath.section][indexPath.row]];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString * headID = @"head";
    TripHeaderView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if (!view) {
        view = [[TripHeaderView alloc] initWithReuseIdentifier:headID];
    }
    view.delegate = self;
    view.headModel = [NSDictionary dictionaryWithObject:self.headModel[section] forKey:@"days"];
//    view.hidden = YES;
//    if ([self.cellModel.data[1] count] == 0) {
//        
//    }
//    if ([self.cellModel.data[2] count] == 0) {
//        
//    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    if ([self.cellModel.data[1] count] == 0) {
//        return 0.01;
//    }
//    if ([self.cellModel.data[2] count] == 0) {
//        return 0;
//    }
    return 40;
}

//侧滑删除
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:NO animated:YES];
//    TripTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
//    cell.modelData = self.dataArray[indexPath.row];
//    self.trip_id = [cell.modelData.userId intValue];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        WS(ws)
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //删除事件
//            [ws.dataArray removeObjectAtIndex:indexPath.row];
//            [ws deleteJourneyDataWithTrip_id:self.trip_id];
            [ws.tableView reloadData];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)addTheDayTrip:(NSString *)str{
    NSString * addDayth = [str substringWithRange:NSMakeRange(1,1)];
    NSLog(@"添加行程%@",addDayth);
    if ([addDayth isEqualToString:@"一"]) {
        self.addToDayth = 1;
    }
    if ([addDayth isEqualToString:@"二"]) {
        self.addToDayth = 2;
    }
    if ([addDayth isEqualToString:@"三"]) {
        self.addToDayth = 3;
    }
    
    ChooseJourneyViewController * chooseJourneyVC = [[ChooseJourneyViewController alloc] init];
    chooseJourneyVC.travelDay = self.addToDayth;
    chooseJourneyVC.trip_id = [NSString stringWithFormat:@"%d",self.trip_id];
    [self.navigationController pushViewController:chooseJourneyVC animated:YES];
}

- (void)nextStepBtnClick{
    NSLog(@"生成行程");
    [self getJournegyName];
//    [self createJourneyName:self.journeyName];
}

- (void)getJournegyName{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请编辑行程名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"name";
        //            textField.textColor = [UIColor blueColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleRoundedRect;
    }];
//    WS(ws)
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //改名事件
        for(UITextField *text in alertController.textFields){
            NSLog(@"text = %@", text.text);
            self.journeyName = text.text;
            [self createJourneyName:self.journeyName];
        }
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

@synthesize coordinate;

@end
